package com.moss.cloud.common.file.utils;

import com.moss.cloud.common.file.exception.StorageErrorType;
import com.moss.cloud.common.file.model.StorageModel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 文件数据处理工具
 *
 * @author 瑾年
 * @date 2023年4月19日
 */
@Slf4j
public class FileDataPreUtil {
    public static final String YYYYMMDD = "yyyyMMdd";

    /**
     * base64转字节数组
     *
     * @param base64Img
     * @return
     */
    public static byte[] base64ToBytes(String base64Img) {
        String fileImg = base64Img.split(",")[1];
        byte[] bytes = null;
        try {
            // 解密base64，转换成数组
            Base64 decoder = new Base64();
            bytes = decoder.decode(fileImg);
        } catch (Exception e) {
            log.error("解密base64，转换成数组失败:{}",e.getMessage());
        }
        return bytes;
    }

    /**
     * 获取原始文件格式
     *
     * @param originalFilename
     * @return
     */
    public static String suffix(String originalFilename) {
        log.info("上传的文件名:{}", originalFilename);
        Boolean flag = StringUtils.isBlank(originalFilename) && originalFilename.lastIndexOf(".") == -1;
        BooleanHandel.trueThrow(flag).throwMessage(StorageErrorType.NAME_EMPTY);
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        return extension.toUpperCase();
    }

    /**
     * 原始文件格式是否允许上传
     *
     * @param originalFilename
     * @param suffix
     */
    public static void isAllowed(String originalFilename, String suffix) {
        String type = suffix(originalFilename);
        if (StringUtils.isNotBlank(suffix)) {
            String[] suffixs = suffix.split(",");
            List<String> types = Arrays.asList(suffixs);
            BooleanHandel.trueThrow(types.contains(type)).throwMessage(StorageErrorType.FORMAT_NOT_ALLOWED);
        }
    }

    /**
     * 获取文件大小
     *
     * @param storageModel
     * @return
     */
    @SneakyThrows
    public static long getSize(StorageModel storageModel) {
        if (storageModel.getInputStream() == null) {
            if (storageModel.getIsBase64()) {
                double len = storageModel.getImgBase64().length();
                return Math.round(len * 0.75);
            } else {
                return storageModel.getMultipartFile().getSize();
            }
        } else {
            return storageModel.getInputStream().available();
        }
    }

    /**
     * 文件大小是否允许上传
     *
     * @param storageModel
     */
    public static void isSizeAllowed(StorageModel storageModel) {
        if (storageModel.getStorageConfig().getSize() != null) {
            long size = getSize(storageModel);
            log.info("文件大小:{}", size);
            Boolean isTrue = size > storageModel.getStorageConfig().getSize();
            BooleanHandel.trueThrow(isTrue).throwMessage(StorageErrorType.TOO_LONG);
        }
    }

    /**
     * 生成文件存储目录
     *
     * @param directory
     */
    public static String genDirectory(String directory) {
        return directory + "/" + getDateAsString() + "/";
    }

    /**
     * 将LocalDate
     *
     * @return
     */
    public static String getDateAsString() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYYMMDD);
        return LocalDate.now().format(formatter);
    }
}
